package com.learning.javaweb_springboot_jwt.config;


import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;

import java.io.IOException;
import com.learning.javaweb_springboot_jwt.util.JwtUtil;


//设置拦截器，拦截所有路径


@WebFilter(filterName = "jwtFilter", urlPatterns = "/*")
public class JwtAuthenticationFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {}

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;

        String token = request.getHeader("Authorization");
        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7); // 移除"Bearer "部分

            //检测令牌是否过期
            if (!JwtUtil.isTokenExpired(token)) {
                //没有过期
                String username = JwtUtil.getUsernameFromToken(token);
                // 这里可以根据需要，设置认证信息到SecurityContext
                // 例如：SecurityContextHolder.getContext().setAuthentication(auth);
            }
        }
        filterChain.doFilter(servletRequest, servletResponse);  // 继续请求链
    }

    @Override
    public void destroy() {}
}

